package io.mvvm.ws;

import io.mvvm.ws.handler.WebSocketAuthHandler;
import io.mvvm.ws.handler.WebSocketDeCoderHandler;
import io.mvvm.ws.handler.WebSocketLoggerHandler;
import io.mvvm.ws.handler.WebSocketMessageHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @program: Netty
 * @description: 通道初始化
 * @author: 潘
 * @create: 2021-04-21 19:23
 **/
@Component
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    private static final String WEB_SOCKET_PATH = "/ws";

    private static final int MAX_CONTENT_LENGTH = 1024 * 62;

    @Resource
    private WebSocketLoggerHandler webSocketLoggerHandler;
    @Resource
    private WebSocketDeCoderHandler webSocketDeCoderHandler;
    @Resource
    private WebSocketAuthHandler webSocketAuthHandler;
    @Resource
    private WebSocketMessageHandler webSocketMessageHandler;

    @Override
    protected void initChannel(SocketChannel sc) throws Exception {
        // HTTP 服务端实现
        sc.pipeline().addLast(new HttpServerCodec());
        //支持写大数据流
        sc.pipeline().addLast(new ChunkedWriteHandler());
        // http聚合器
        sc.pipeline().addLast(new HttpObjectAggregator(MAX_CONTENT_LENGTH));
        // websocket支持,设置路由
        sc.pipeline().addLast(new WebSocketServerProtocolHandler(WEB_SOCKET_PATH));

        /* 自定义的处理器 */
        // 日志打印
        sc.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
//        sc.pipeline().addLast(WebSocketLoggerHandler.HANDLER_NAME, webSocketLoggerHandler);
        // 解码器
        sc.pipeline().addLast(WebSocketDeCoderHandler.HANDLER_NAME, webSocketDeCoderHandler);
        // 鉴权处理器
        sc.pipeline().addLast(WebSocketAuthHandler.HANDLER_NAME, webSocketAuthHandler);
        // 消息处理器
        sc.pipeline().addLast(WebSocketMessageHandler.HANDLER_NAME, webSocketMessageHandler);
    }
}
